package com.zhuss.aop;

import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * sql 拦截器
 * @author zhushanshuo
 * @since 2020-02-23 10:05
 *
 */

@Component
@Intercepts(
		@Signature(
				type = Executor.class, 
				method = "query",
				args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
				)
		)
public class MybatisSqlInterceptor implements Interceptor {

    Logger  LOGGER = LoggerFactory.getLogger(MybatisSqlInterceptor.class);
    
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 拦截sql
        Object[] args = invocation.getArgs();
        MappedStatement statement = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = statement.getBoundSql(parameterObject);
        String sql = boundSql.getSql();
        sql = sql.replaceAll("\\n", " ");
        sql = sql.replaceAll("\\t", " ");
        while (sql.contains("  ")) {
        	sql = sql.replaceAll("  ", " ");
        }
        //LOGGER.info("获取到的SQL: "+sql);
        //LOGGER.info("参数: " + JsonUtil.toJson(parameterObject));
        if ("".equals(sql)) {
        	Object result = invocation.proceed();
        	//LOGGER.info("结果: " + JsonUtil.toJson(result));
            return result;
        }
        // 返回
        Object result = invocation.proceed();
        //LOGGER.info("结果: " + JsonUtil.toJson(result));
        return result;
    }
 
    @Override
    public Object plugin(Object obj) {
        return Plugin.wrap(obj, this);
    }
 
    @Override
    public void setProperties(Properties arg0) {}

}